package com.ubi.core.log;

import com.ubi.core.framework.request.RequestContext;
import com.ubi.core.framework.spring.ControllerHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TrackRequestProcessInterceptor extends HandlerInterceptorAdapter {

    private final Logger logger = LoggerFactory.getLogger(TrackRequestProcessInterceptor.class);

    private RequestContext requestContext;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Track track = ControllerHelper.findMethodOrClassLevelAnnotation(handler, Track.class);
        if (track == null) {
            return;
        }
        trackRequestProcess(track);
    }

    private void trackRequestProcess(Track track) {
        if (track.warningThresholdInMs() <= 0) {
            return;
        }
        long elapsedTime = System.currentTimeMillis() - requestContext.getRequestDate().getTime();
        if (elapsedTime > track.warningThresholdInMs()) {
            logger.warn("process took longer than track threshold, elapsedTime(ms)={}", elapsedTime);
        }
    }

    @Autowired
    public void setRequestContext(RequestContext requestContext) {
        this.requestContext = requestContext;
    }
}
